//
//  OrderRootCell.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/6/17.
//

import UIKit

class OrderRootCell: UITableViewCell {

    typealias OrderCellActionBlock = (_ actionType:OrderActionType) -> Void
    var orderCellActionBlock : OrderCellActionBlock!
    
    @IBOutlet weak var lineView: UIView!
    @IBOutlet weak var labelsView: UIView!
    @IBOutlet weak var labelsHeight: NSLayoutConstraint!
    @IBOutlet weak var mailNoLab: UILabel!
    @IBOutlet weak var senderNameLab: UILabel!
    @IBOutlet weak var collectNameLab: UILabel!
    @IBOutlet weak var orderStateLab: UILabel!
    @IBOutlet weak var collectCity: UILabel!
    @IBOutlet weak var senderCityLab: UILabel!
    @IBOutlet weak var addressLab: UILabel!
    @IBOutlet weak var addressDetailLab: UILabel!
    @IBOutlet weak var timerLab: UILabel!
    @IBOutlet weak var callPhoneLab: UIButton!
    @IBOutlet weak var btnsView: UIView!
    @IBOutlet weak var titleWidthValue: NSLayoutConstraint!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var btnView: UIView!
    @IBOutlet weak var btnViewHeight: NSLayoutConstraint!
    @IBOutlet weak var callPhoneBtnWidth: NSLayoutConstraint!

    var orderInfoModel:OrderListModel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentView.backgroundColor = UIColor.init(named: "#F5F6F5")
        self.bgView.layer.shadowColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
        self.bgView.layer.shadowOffset = CGSize.init(width: 0, height: 1)
        bgView.layer.shadowOpacity = 1
        bgView.layer.shadowRadius = 2
        bgView.layer.cornerRadius = 5
        
        senderNameLab.font = UIFont.boldSystemFont(ofSize: 16)
        collectNameLab.font = UIFont.boldSystemFont(ofSize: 16)
        orderStateLab.font = UIFont.boldSystemFont(ofSize: 14)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func setOrderInfoModel(InfoModel:OrderListModel) {
        orderInfoModel = InfoModel
        mailNoLab.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_hint_mailNo) + orderInfoModel.mailSn
        senderCityLab.text = orderInfoModel.senderName
        senderNameLab.text = orderInfoModel.senderCity
        collectNameLab.text = orderInfoModel.receiverCity
        collectCity.text = orderInfoModel.receiverName
        let str = UserDefaults.standard.string(forKey: LanguageHeader.MySystemLanguage)
        if (str == LanguageHeader.BurmaLanguage) {
            senderCityLab.changeLineSpaceForLabel(space: 6.0)
            collectCity.changeLineSpaceForLabel(space: 6.0)
        } else {
            senderCityLab.changeLineSpaceForLabel(space: 4.0)
            collectCity.changeLineSpaceForLabel(space: 4.0)
        }
        senderCityLab.textAlignment = .center
        collectCity.textAlignment = .center
        
        orderStateLab.text = orderInfoModel.getOrderState()
        timerLab.text = orderInfoModel.createTime.getCurrentTimerByTimezone(dateFormat: "yyyy-MM-dd HH:mm:ss")
        addressLab.text = orderInfoModel.getOrderState() + ":"
        titleWidthValue.constant = addressLab.text?.getWidth(UIFont.systemFont(ofSize: 12)) ?? 0 + 5
        
        let userRole = WLUserModel.getUserType()
        if userRole == "1" {
            if orderInfoModel.orderStatus == Constants.order_waitColloct {
                callPhoneLab.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_Call_sender), for: .normal)
                callPhoneLab.setImage(UIImage.init(named: "send_Phone"), for: .normal)
                callPhoneLab.isHidden = false
                callPhoneBtnWidth.constant = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_Call_sender).getWidth(UIFont.systemFont(ofSize: 11)) + 20
            } else if orderInfoModel.orderStatus == Constants.order_waitDelivery {
                callPhoneLab.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_Call_colloct), for: .normal)
                callPhoneLab.setImage(UIImage.init(named: "revece_Phone"), for: .normal)
                callPhoneBtnWidth.constant = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_Call_sender).getWidth(UIFont.systemFont(ofSize: 11)) + 20
            } else {
                callPhoneLab.isHidden = true
            }
        } else {
            callPhoneLab.isHidden = true
        }
        //订单状态：-1->已删除;0->已取消；1->待接单；3->待揽收；5-待分拣；8->仓储中；;10->待发件；13-运输中待接单 15 代派件 16已签收 17 已送车站 18 已送机场
        let userType = WLUserModel.getUserType()
        //3-揽件员,4-分拣员,5-派件员,6-app用户,7-app大客户
        let tag = orderInfoModel.orderStatus
        if userType == "2" {
            if tag == Constants.order_waitReceive || tag == Constants.order_waitColloct ||
                tag == Constants.order_cancel || tag == Constants.order_waitSorting ||
                tag == Constants.order_storage || tag == Constants.order_waitSend ||
                tag == Constants.order_waitDelivery || tag == Constants.order_signed ||
                tag == Constants.order_station || tag == Constants.order_air
            {
                btnViewHeight.constant = 37
                btnView.isHidden = false
                lineView.isHidden = false
            } else {
                btnViewHeight.constant = 0.1
                btnView.isHidden = true
                lineView.isHidden = true
            }
        } else {
            if tag == Constants.order_waitColloct ||  tag == Constants.order_waitSorting ||
                tag == Constants.order_storage ||  tag == Constants.order_waitDelivery {
                btnViewHeight.constant = 37
                btnView.isHidden = false
                lineView.isHidden = false
            } else {
                btnViewHeight.constant = 0.1
                btnView.isHidden = true
                lineView.isHidden = true
            }
        }
        
        //待揽件
        if userType == "2" {
            if orderInfoModel.orderStatus == Constants.order_waitColloct || orderInfoModel.orderStatus == Constants.order_waitDelivery ||
                orderInfoModel.orderStatus == Constants.order_signed {
                let text = NSMutableAttributedString.init(string: orderInfoModel.statusCopywriting)
                text.yy_color = UIColor.init(hexString: "#6C6C6C")
                
                let str = UserDefaults.standard.string(forKey:LanguageHeader.MySystemLanguage)
                if (str == LanguageHeader.BurmaLanguage) {
                    text.yy_lineSpacing = 5;
                } else {
                    text.yy_lineSpacing = 4;
                }
                let textsStr:NSString = (text.string) as NSString
                if orderInfoModel.cwPhone.count <= 0 {
                    orderInfoModel.cwPhone = ""
                } else {
                    if orderInfoModel.statusCopywriting.contains(orderInfoModel.cwPhone) {
                        let tap = UITapGestureRecognizer.init(target: self, action: #selector(callPhone))
                        addressDetailLab.addGestureRecognizer(tap)
                        addressDetailLab.isUserInteractionEnabled = true
                    }
                }
                text.yy_setTextHighlight(textsStr.range(of: orderInfoModel.cwPhone), color: UIColor.init(hexString: "#0078F1"), backgroundColor: UIColor.clear) { (containerView, text, range, rect) in
                    if self.orderCellActionBlock != nil {
                        self.orderCellActionBlock(OrderActionType.Order_callSenderPhone_Type)
                    }
                }
                addressDetailLab.attributedText = text
            } else {
                addressDetailLab.text = orderInfoModel.statusCopywriting
                addressDetailLab.isUserInteractionEnabled = false
            }
        } else {
            addressDetailLab.text = orderInfoModel.statusCopywriting
            let str = UserDefaults.standard.string(forKey: LanguageHeader.MySystemLanguage)
            if (str == LanguageHeader.BurmaLanguage) {
                addressDetailLab.changeLineSpaceForLabel(space: 6.0)
            } else {
                addressDetailLab.changeLineSpaceForLabel(space: 4.0)
            }
            addressDetailLab.isUserInteractionEnabled = false
        }
        self.addMarkLabel()
        self.addMarkBtn()
    }
    
    @objc func callPhone() {
        let telURL:URL = URL.init(string: "tel:"+orderInfoModel.cwPhone)!
        UIApplication.shared.open(telURL, options:[:]) { (state) in
            
        }
    }
    
    @objc func clickBtn(sender:MarkBtn) {
        if  (orderCellActionBlock != nil) {
            let actionStr:String = sender.titleLabel?.text ?? ""
            if (actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_logistics_detail) ||
            actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_logistics_after) ||
            actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_logistics_newafter)) {
                orderCellActionBlock(OrderActionType.Order_LogisticsMsg_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_delete) {
                orderCellActionBlock(OrderActionType.Order_Delete_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_operate_cancelOrder) {
                orderCellActionBlock(OrderActionType.Order_Cancel_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_print) {
                orderCellActionBlock(OrderActionType.Order_Print_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_operate_modification) {
                orderCellActionBlock(OrderActionType.Order_Edit_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_operate_collect) {
                orderCellActionBlock(OrderActionType.Order_Collect_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_Sorting) {
                orderCellActionBlock(OrderActionType.Order_Sorting_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_operate_income) {
                orderCellActionBlock(OrderActionType.Order_EnterLibrary_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_operate_leave) {
                orderCellActionBlock(OrderActionType.Order_LeaveLibrary_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_operate_rejection) {
                orderCellActionBlock(OrderActionType.Order_Repel_Type)
            } else if actionStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_state_sign) {
                orderCellActionBlock(OrderActionType.Order_Sign_Type)
            }
        }
    }

    func addMarkLabel() {
        for view in labelsView.subviews {
            if view is MarkLabel || view is TransitView {
                view.removeFromSuperview()
            }
        }
        
        let titleArray = orderInfoModel.getAllSignStr()
        var xOffSet:CGFloat = 10
        var yOffSet:CGFloat = 0
        let height:CGFloat = 25
        for titleStr in titleArray {
            let titleLab:MarkLabel = MarkLabel.createSignLabWithText(titleStr: titleStr)
            let width = titleStr.getWidth(UIFont.systemFont(ofSize: 11))
            self.labelsView.addSubview(titleLab)
            if xOffSet + width > Constants.screenWidth - 35 {
                xOffSet = 0
                yOffSet += height
            }
            titleLab.snp.makeConstraints { (make) in
                make.left.equalTo(self.labelsView.snp.left).offset(xOffSet)
                make.top.equalTo(self.labelsView.snp.top).offset(yOffSet)
                make.width.equalTo(width)
                make.height.equalTo(height - 5)
            }
            xOffSet = xOffSet + width + 10
            titleLab.textColor = UIColor.init(hexString: "#FFFFFF")
            if titleStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_deliver_airport) ||
            titleStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_deliver_stationt) {
                titleLab.backgroundColor = UIColor.init(hexString: "#0078F1")
            } else if titleStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_state_worry){
                titleLab.backgroundColor = UIColor.init(hexString: "#FF3737")
            } else if titleStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_support){
                titleLab.backgroundColor = UIColor.init(hexString: "#E5C253")
            } else if titleStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_state_retreat){
                titleLab.backgroundColor = UIColor.init(hexString: "#A6A6A6")
            } else if titleStr == ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_collectionDelivery){
                titleLab.backgroundColor = UIColor.init(hexString: "#F69423")
            }
        }
        if titleArray.count != 0 {
            labelsHeight.constant = yOffSet + 15 + 5
        } else {
            labelsHeight.constant = yOffSet
        }
    }
    
    func addMarkBtn() {
        for view in btnView.subviews {
            if view is MarkBtn {
                view.removeFromSuperview()
            }
        }
        let titleArray = orderInfoModel.getAllBtnStr()
        var xOffSet:CGFloat = 0
        for titleStr in titleArray {
            let titleLab:MarkBtn = MarkBtn.createSignBtnWithText(titleStr: titleStr)
            titleLab.addTarget(self, action: #selector(clickBtn), for: .touchUpInside)
            var width = titleStr.getWidth(UIFont.systemFont(ofSize: 11)) + 10
            if width < 60 {
                width = 60
            }
            btnsView.addSubview(titleLab)
            titleLab.snp.makeConstraints { (make) in
                make.width.equalTo(width)
                make.height.equalTo(21.5)
                make.centerY.equalTo(self.btnView.snp.centerY)
                make.right.equalTo(self.btnsView.snp.right).offset(-xOffSet)
            }
            titleLab.setTitle(titleStr, for: .normal)
            xOffSet = xOffSet + width + 10
        }
    }
    
    @IBAction func clickCallPhoneBtn(_ sender: UIButton) {
        if orderInfoModel.orderStatus == "3" {
            let telURL:URL = URL.init(string: "tel:" + orderInfoModel.senderPhoneCode + orderInfoModel.senderPhone)!
            UIApplication.shared.open(telURL, options: [:]) { (state) in
                
            }
        } else if orderInfoModel.orderStatus == "15" {
            let telURL:URL = URL.init(string: "tel:" + orderInfoModel.receiverPhoneCode + orderInfoModel.receiverPhone)!
            UIApplication.shared.open(telURL, options: [:]) { (state) in
                
            }
        }
    }
}
